import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'
import { IDetailHeaderTab } from '@shared/interfaces/common'
import { NzModalService, NzIconService  } from 'ng-zorro-antd'
import { Router, ActivatedRoute } from '@angular/router'

@Component({
  selector: 'app-detail-header',
  templateUrl: './detail-header.component.html',
  styleUrls: ['./detail-header.component.less'],
})
export class DetailHeaderComponent implements OnInit {
  @ViewChild('tabScroll', {read: ElementRef}) private tabScroll: ElementRef
  public titleNzSm = { span: 18 }
  public titleNzMd = { span: 18 }
  public titleNzLg = { span: 18 }
  public btnsNzSm = { span: 6, offset: 0 }
  public btnsNzMd = { span: 6, offset: 0 }
  public btnsNzLg = { span: 6, offset: 0 }

  public ifEdit: boolean

  @Input() ifEditable = true

  @Input() tabs: IDetailHeaderTab[]

  @Input() title: string

  @Input() hideIcon = false

  @Output() edit = new EventEmitter()
  @Output() cancel = new EventEmitter()
  @Output() save = new EventEmitter()
  // Open this one to use highlight the selected button in the group, remember to uncommnet the code in below as well
  selectTab: string
  constructor(
    private modal: NzModalService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    // get the current parent router path not include tab url.
    let currentUrl = ''
    this.route.url.subscribe(values => {
      const urlTree = this.router.parseUrl(this.router.url)
      const fullUrlWithoutParams = urlTree.root.children['primary'].segments.map(it => it.path).join('/')
      currentUrl = values[values.length - 1].path
      // find the index of the path from full url
      const index = fullUrlWithoutParams.indexOf(currentUrl)
      // use substring to set the current path url
      this.selectTab = `.${fullUrlWithoutParams.substr(index + currentUrl.length)}`
    })
  }

  showButtons(): void {
    if (!this.ifEdit) {
      this.ifEdit = true
    }
    this.edit.next()
  }

  changeRouter(url): void {
    if (this.ifEdit) {
      this.modal.confirm({
        nzTitle: '您当前正在编辑，确定要跳转吗?',
        nzOnOk: () => {
          this.router.navigate([url], { relativeTo: this.route})
        },
        nzOnCancel: () => { console.log('啥也不做') }
      })
    } else {
      this.router.navigate([url], { relativeTo: this.route })
    }
  }

  handleBack(): void {
    this.cancel.next()
    this.hideButtons()
  }

  handleSave(): void {
    this.save.next()
  }

  scrollTo(position: string): void {
    const scrollToX = (position === 'left') ? 0 : this.tabScroll.nativeElement.scrollWidth
    this.tabScroll.nativeElement.scrollTo({ left: scrollToX , behavior: 'smooth' })
  }

  hideButtons() {
    this.ifEdit = false
  }
}
